package com.zxy.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxy.common.BindingResultUtil;
import com.zxy.common.ResultData;
import com.zxy.dto.PersonCount;
import com.zxy.dto.SexCount;
import com.zxy.entity.Login;
import com.zxy.entity.Student;
import com.zxy.mapper.StudentMapper;
import com.zxy.service.IStudentService;
import com.zxy.utils.JWTUtils;
import lombok.AllArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Zxy
 * @since 2021-05-11
 */
@RestController
@RequestMapping("/student")
@AllArgsConstructor
public class StudentController {

    private final IStudentService studentService;

    private final StudentMapper studentMapper;

    public static String code = "";

    // 添加学生（注册请求）
    @PostMapping("/add")
    public ResultData add(@Validated @RequestBody Student student, BindingResult result) {
        BindingResultUtil.validate(result);
        if (findByIdCard(student.getIdCard()) != null) {
            return ResultData.fail("学生已经存在，请勿重复添加");
        } else {
            String[] split = UUID.randomUUID().toString().split("-");
            // 注册时自动生成一卡通账号
            student.setCard(split[split.length - 1]);
            boolean save = studentService.save(student);
            if (save) {
                return ResultData.success(save);
            } else {
                return ResultData.fail("保存失败，请联系网站管理员");
            }
        }
    }

    // 根据学生身份证号查询，防止数据重复
    private Student findByIdCard(String card) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("id_card", card);
        return studentService.getOne(wrapper);
    }

    // 查询全部学生
    @GetMapping("/findlist")
    public ResultData findList(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<Student> page = new Page<>(current, size);
        Page<Student> studentPage = studentService.page(page);
        if (studentPage != null) {
            return ResultData.success(studentPage);
        } else {
            return ResultData.fail("数据获取失败，请联系网站管理员");
        }
    }

    // 根据用户id查询用户
    @GetMapping("/findbyid")
    public ResultData findById(@RequestParam("id") Integer id) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Student student = studentService.getOne(wrapper);
        if (student != null) {
            return ResultData.success(student);
        } else {
            return ResultData.fail("数据获取失败，请联系网站管理员");
        }
    }

    // 根据id修改学生信息
    @PutMapping("/updatebyid")
    public ResultData updateStudent(@Validated @RequestBody Student student, BindingResult result) {
        BindingResultUtil.validate(result);
        boolean update = studentService.updateById(student);
        if (update) {
            return ResultData.success(update);
        } else {
            return ResultData.fail("保存失败，请联系网站管理员");
        }
    }

    // 根据id删除学生信息
    @DeleteMapping("/deletebyid")
    public ResultData deleteById(@RequestParam("id") Integer id) {
        boolean remove = studentService.removeById(id);
        if (remove) {
            return ResultData.success(remove);
        } else {
            return ResultData.fail("保存失败，请联系网站管理员");
        }
    }

    // 管理员审核学生状态，携带学生id和状态id
    @GetMapping("/exam")
    public ResultData toExamine(@RequestParam("stuId") Integer stuId, @RequestParam("status") Integer status) {
        // 前端点击审核通过，发送id为1，更改数据库
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("id", stuId);
        Student student = studentService.getOne(wrapper);
        // 学生存在，更新状态
        if (student != null) {
            int i = studentService.stuExam(stuId, status);
            return ResultData.success(i);
        } else {
            return ResultData.fail("学生不存在");
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResultData login(@RequestBody Login login) {
        if (!login.getCode().equals(code)) {
            return ResultData.fail("验证码不正确，请检查后重新输入");
        }
        // 判断学生是否被激活
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("id_card", login.getIdCard());
        wrapper.eq("password", login.getPassword());
        Student stu = studentService.getOne(wrapper);
        // 验证登录用户是学生还是管理员
        if (stu == null) {
            return ResultData.fail("用户不存在，请检查后重新输入");
        } else {
            if (stu.getStatus() == 0) {
                return ResultData.fail("用户未激活，请联系管理员激活");
            } else {
                HashMap<String, String> map = new HashMap<>();
                map.put("id_card", login.getIdCard());
                String token = JWTUtils.getToken(map);
                stu.setToken(token);
                return ResultData.success(stu);
            }
        }
    }

    // 获取验证码
    @GetMapping("/code")
    public void code(HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        code = lineCaptcha.getCode();
        lineCaptcha.write(response.getOutputStream());
    }

    // 统计男女生人数
    @GetMapping("/countsex")
    public ResultData countSex() {
        List<SexCount> sexCounts = studentMapper.countBySexCount();
        return ResultData.success(sexCounts);
    }

    // 统计总人数
    @GetMapping("/countperson")
    public ResultData countPerson() {
        PersonCount count = studentMapper.personCount();
        return ResultData.success(count);
    }

    // 统计18-24之间人数比例
    @GetMapping("/eighteento")
    public ResultData countEight() {
        PersonCount count = studentMapper.eighteenToTwentyFour();
        return ResultData.success(count);
    }

    // 申请一卡通卡号
    @GetMapping("/applycard")
    public ResultData applyCard(@RequestParam("idCard") String idCard, @RequestParam("card") String card) {
        // 更新当前学生所持有一卡通信息状态
        int info = studentMapper.updateCardInfo(idCard, card);
        return ResultData.success(info);
    }
}
